<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "{{%zs_customer_cat}}".
 *
 * @property integer $cat_id
 * @property string $cat_name
 * @property string $cat_logo
 * @property integer $is_show
 */
class CustomerCat extends \yii\db\ActiveRecord
{
    public $logo;
    public $createChild = false;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%zs_customer_cat}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['cat_name'], 'required'],
            [['is_show' , 'parent_id'], 'integer'],
            [['cat_name'], 'string', 'max' => 20],
            [['cat_logo'], 'string', 'max' => 200]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'cat_id' => 'Cat ID',
            'cat_name' => '分类名称',
            'cat_logo' => '分类logo',
            'is_show' => '是否展示',
            'parent_id' => '上级分类'
        ];
    }

    public function upload()
    {
        $path = 'uploads/' . $this->logo->baseName.'.'.$this->logo->extension;
        $this->cat_logo = $path;
        $this->logo->saveAs($path);
        return true;
    }

    public static function getCat($parent_id = 0)
    {
        $data = self::find()->all();
//        var_dump($data);die;
        $result = [];
        foreach( $data as $v){
            $result[$v['cat_id']] = $v['cat_name'];
        }
        return $result;
    }


    public static function getCatArr()
    {
        $data = self::find()->asArray()->all();

        $result = [];
        foreach($data as $v){
            if($v['parent_id'] == 0){
                $result[$v['cat_id']] = ['name' => $v['cat_name'] ,];
            }else{
                if(isset($result[$v['parent_id']])){
                    $result[$v['parent_id']]['child'][$v['cat_id']] = $v['cat_name'];
                }else{
                    $result[$v['parent_id']] = ['name' => $v['cat_name'] ];
                    $result[$v['parent_id']]['child'][$v['cat_id']] = $v['cat_name'];
                }
            }

        }
        return $result;
    }

    public static function getNameById($cid = 0)
    {
        $model = CustomerCat::findOne(['cat_id' => $cid]);
        if($model){
            return $model->cat_name;
        }else{
            return '';
        }
    }



}
